package tongwentongshu.com.app.map;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.AlphaAnimation;
import com.amap.api.maps.model.animation.Animation;

import java.util.ArrayList;
import java.util.List;

import tongwentongshu.com.app.R;
import tongwentongshu.com.app.bean.PioBean;
import tongwentongshu.com.app.contract.MapMainContract;

/**
 * 在线程里进行Marker的添加和动画
 * Created by XiongBin on 2017/6/20.
 */

public class ClusterControl implements AMap.OnMarkerClickListener, AMap.OnCameraChangeListener {
    private AMap mAMap;
    private Context mContext;
    private HandlerThread mMarkerHandlerThread = new HandlerThread("addMarker");//添加marker的线程
    private Handler mMarkerhandler;
    private LruCache<String, BitmapDescriptor> mLruCache;
    private List<PioBean.DataBean.AreaarrayBean> areaarray;//一级区
    private List<PioBean.DataBean.AreaarrayBean> tradingarray;//二级商圈
    private List<PioBean.DataBean.AreaarrayBean> aoiarray;//三级aoi
    private List<Marker> mAddMarkers = new ArrayList<Marker>();//存放地图上的marker
    private int Hierarchy = 1;//层级
    private MapMainContract.View mv;

    /**
     * 构造函数
     *
     * @param amap
     * @param context
     */
    public ClusterControl(AMap amap, Context context) {
        this(amap, null, context, null);
    }

    /**
     * 构造函数,批量添加聚合元素时,调用此构造函数
     *
     * @param amap
     * @param context
     */
    public ClusterControl(AMap amap, PioBean pioBean,
                          Context context, MapMainContract.View mp) {
        mLruCache = new LruCache<String, BitmapDescriptor>(80) {
            protected void entryRemoved(boolean evicted, String key, BitmapDescriptor oldValue, BitmapDescriptor newValue) {
                oldValue.getBitmap().recycle();
            }
        };
        if (pioBean != null) {
            this.areaarray = pioBean.getData().getAreaarray();
            this.tradingarray = pioBean.getData().getTradingarray();
            this.aoiarray = pioBean.getData().getAoiarray();
        } else {
            this.areaarray = new ArrayList<PioBean.DataBean.AreaarrayBean>();
            this.tradingarray = new ArrayList<PioBean.DataBean.AreaarrayBean>();
            this.aoiarray = new ArrayList<PioBean.DataBean.AreaarrayBean>();
        }

        mContext = context;
        this.mv = mp;
        this.mAMap = amap;
        amap.setOnCameraChangeListener(this);
        initThreadHandler();
        drawMarkers();
    }

    /**
     * 对点进行绘制
     */
    private void drawMarkers() {
        mMarkerhandler.removeMessages(MarkerHandler.ADD_MARKER_LIST);
        mMarkerhandler.sendEmptyMessage(MarkerHandler.ADD_MARKER_LIST);
    }

    //初始化Handler
    private void initThreadHandler() {
        mMarkerHandlerThread.start();
        mMarkerhandler = new MarkerHandler(mMarkerHandlerThread.getLooper());
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        Log.e("onCameraChange", "onCameraChange: " + mAMap.getCameraPosition().zoom);

        if (mAMap.getCameraPosition().zoom > 15) {
            Hierarchy = 3;
            mMarkerhandler.removeMessages(MarkerHandler.CALCULATE_CLUSTER);
            mMarkerhandler.sendEmptyMessage(MarkerHandler.CALCULATE_CLUSTER);
        } else if (mAMap.getCameraPosition().zoom > 13 && mAMap.getCameraPosition().zoom <= 15) {
            Hierarchy = 2;
            mMarkerhandler.removeMessages(MarkerHandler.CALCULATE_CLUSTER);
            mMarkerhandler.sendEmptyMessage(MarkerHandler.CALCULATE_CLUSTER);
        } else {
            Hierarchy = 1;
            drawMarkers();
        }
        mv.setHierarchy(Hierarchy);
    }

    /**
     * 处理market添加，更新等操作
     */
    class MarkerHandler extends Handler {

        static final int ADD_MARKER_LIST = 1;//生成区marker
        static final int CALCULATE_CLUSTER = 2;//判定二级兴趣点marker
        static final int DROW_CLUSTER = 3;//生成二级兴趣点marker

        MarkerHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message message) {

            switch (message.what) {
                case ADD_MARKER_LIST:
                    addClusterToMap(areaarray);
                    break;
                case CALCULATE_CLUSTER:
                    calculateClusters();
                    break;
                case DROW_CLUSTER:
                    List<PioBean.DataBean.AreaarrayBean> clusters = (List<PioBean.DataBean.AreaarrayBean>) message.obj;
                    addClusterToMap(clusters);
                    break;
            }
        }
    }

    private void calculateClusters() {
        LatLngBounds visibleBounds = mAMap.getProjection().getVisibleRegion().latLngBounds;
        List<PioBean.DataBean.AreaarrayBean> clusters = new ArrayList<PioBean.DataBean.AreaarrayBean>();
        for (PioBean.DataBean.AreaarrayBean clusterItem : (Hierarchy == 3 ? aoiarray : tradingarray)) {
            LatLng latlng = new LatLng(Double.valueOf(clusterItem.getLatitude()), Double.valueOf(clusterItem.getLongitude()));
            if (visibleBounds.contains(latlng)) {
                clusters.add(clusterItem);
            }
        }
        mMarkerhandler.removeMessages(MarkerHandler.DROW_CLUSTER);
        Message message = Message.obtain();
        message.what = MarkerHandler.DROW_CLUSTER;
        message.obj = clusters;
        mMarkerhandler.sendMessage(message);
    }

    /**
     * 将区县元素添加至地图上
     */
    private void addClusterToMap(List<PioBean.DataBean.AreaarrayBean> clusters) {
        List<Marker> clustersRemove = new ArrayList<>();
        List<PioBean.DataBean.AreaarrayBean> clustersAdd = new ArrayList<>();
        int len = clusters.size() > mAddMarkers.size() ? clusters.size() : mAddMarkers.size();

        for (int i = 0; i < clusters.size(); i++) {
            PioBean.DataBean.AreaarrayBean oldPda = null;
            PioBean.DataBean.AreaarrayBean newPda = null;
            newPda = clusters.get(i);
            boolean lenb = false;
            for (int j = 0; j < mAddMarkers.size(); j++) {
                oldPda = (PioBean.DataBean.AreaarrayBean) mAddMarkers.get(j).getObject();
                if (oldPda.getAdname().equals(newPda.getAdname())) {
                    lenb = true;
                }
            }
            if (!lenb) {
                clustersAdd.add(newPda);
            }
        }
        for (int i = 0; i < mAddMarkers.size(); i++) {
            PioBean.DataBean.AreaarrayBean oldPda = null;
            PioBean.DataBean.AreaarrayBean newPda = null;
            oldPda = (PioBean.DataBean.AreaarrayBean) mAddMarkers.get(i).getObject();
            boolean lenb = false;
            for (int j = 0; j < clusters.size(); j++) {
                newPda = clusters.get(j);
                if (oldPda.getAdname().equals(newPda.getAdname())) {
                    lenb = true;
                }
            }
            if (!lenb) {
                clustersRemove.add(mAddMarkers.get(i));
            }
        }
        for (Marker marker : clustersRemove) {
            marker.remove();
        }
        mAddMarkers.removeAll(clustersRemove);
//        ArrayList<Marker> removeMarkers = new ArrayList<>();
//        removeMarkers.addAll(clustersRemove);
//        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
//        MyAnimationListener myAnimationListener = new MyAnimationListener(removeMarkers);
//        for (Marker marker : removeMarkers) {
//            marker.setAnimation(alphaAnimation);
//            marker.setAnimationListener(myAnimationListener);
//            marker.startAnimation();
//        }

        for (int i = 0; i < clustersAdd.size(); i++) {
            addSingleClusterToMap(clustersAdd.get(i));
        }
    }

    private AlphaAnimation mADDAnimation = new AlphaAnimation(0, 1);

    /**
     * 将单个Marker添加至地图显示
     *
     * @param cluster
     */
    private void addSingleClusterToMap(PioBean.DataBean.AreaarrayBean cluster) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.anchor(0.5f, 0.5f)
                .icon(getBitmapDes(cluster)).position(new LatLng(Double.valueOf(cluster.getLatitude()), Double.valueOf(cluster.getLongitude())));
        Marker marker = mAMap.addMarker(markerOptions);
        marker.setAnimation(mADDAnimation);
        marker.setObject(cluster);

        marker.startAnimation();
        mAddMarkers.add(marker);

    }

    /**
     * 获取每个marker的绘制样式
     */
    private BitmapDescriptor getBitmapDes(PioBean.DataBean.AreaarrayBean dis) {
        BitmapDescriptor bitmapDescriptor;
//                = mLruCache.get(dis.getAdname());
//        if (bitmapDescriptor == null) {
        View view;

        if (Hierarchy == 1 || Hierarchy == 2) {
            view = View.inflate(mContext, R.layout.view_day, null);
            TextView tv_path = (TextView) view.findViewById(R.id.tv_path);
            TextView tv_books = (TextView) view.findViewById(R.id.tv_books);
            tv_path.setText(dis.getAdname());
            tv_books.setText(dis.getBook_num() + "本书籍");
        } else {
            view = View.inflate(mContext, R.layout.view_aoi, null);
            TextView tv_path = (TextView) view.findViewById(R.id.tv_path);
            tv_path.setText(dis.getAdname() + "\n共" + dis.getBook_num() + "本书籍");
        }

        bitmapDescriptor = BitmapDescriptorFactory.fromView(view);
//        mLruCache.put(dis.getAdname(), bitmapDescriptor);
//        }
        return bitmapDescriptor;
    }

    /**
     * marker渐变动画，动画结束后将Marker删除
     */
    class MyAnimationListener implements Animation.AnimationListener {
        private List<Marker> mRemoveMarkers;

        MyAnimationListener(List<Marker> removeMarkers) {
            mRemoveMarkers = removeMarkers;
        }

        @Override
        public void onAnimationStart() {

        }

        @Override
        public void onAnimationEnd() {
            for (Marker marker : mRemoveMarkers) {
                marker.remove();
            }
            mRemoveMarkers.removeAll(mRemoveMarkers);
        }
    }

    public void onDestroy() {
        mMarkerhandler.removeCallbacksAndMessages(null);
        mMarkerHandlerThread.quit();
        for (Marker marker : mAddMarkers) {
            marker.remove();
        }
        mAddMarkers.clear();
        mLruCache.evictAll();
    }
}
